/*
 * tarm_iic.c
 *
 *  Created on: 2019年12月10日
 *      Author: tinnu
 */


#include <tarm_CTIMER_PWM.h>

#define CTIMER_CLK_FREQ CLOCK_GetCTimerClkFreq(3U)
volatile uint32_t g_pwmPeriod   = 0U;
volatile uint32_t g_pulsePeriod = 0U;

status_t CTIMER_GetPwmPeriodValue(uint32_t pwmFreqHz, uint8_t dutyCyclePercent, uint32_t timerClock_Hz)
{
    /* Calculate PWM period match value */
    g_pwmPeriod = (timerClock_Hz / pwmFreqHz) - 1;

    /* Calculate pulse width match value */
    if (dutyCyclePercent == 0)
    {
        g_pulsePeriod = g_pwmPeriod + 1;
    }
    else
    {
        g_pulsePeriod = (g_pwmPeriod * (100 - dutyCyclePercent)) / 100;
    }
    return kStatus_Success;
}

void CTIMER_PWM_Init(void)
{
	CLOCK_AttachClk(kFRO1M_to_CTIMER3);
	ctimer_config_t config;
	/* CTimer0 counter uses the AHB clock, some CTimer1 modules use the Aysnc clock */
	uint32_t srcClock_Hz = CTIMER_CLK_FREQ;

//	PRINTF("CTimer example to generate a PWM signal\r\n");

	CTIMER_GetDefaultConfig(&config);
	uint32_t timerClock = srcClock_Hz / (config.prescale + 1);

	CTIMER_Init(CTIMER3, &config);

	/* Get the PWM period match value and pulse width match value of 20Khz PWM signal with 20% dutycycle */
	CTIMER_GetPwmPeriodValue(20000, 20, timerClock);
	CTIMER_SetupPwmPeriod(CTIMER3, kCTIMER_Match_3, g_pwmPeriod, g_pulsePeriod, false);
	CTIMER_StartTimer(CTIMER3);
}
